package com.chuangke.lowcode.component.handle;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chuangke.common.constant.ColumnConstants;
import com.chuangke.common.enums.OrderStatusEnum;
import com.chuangke.common.exception.ChuangkeException;
import com.chuangke.common.utils.SpringContextUtil;
import com.chuangke.framework.model.BillModel;
import com.chuangke.lowcode.LowCodeContext;
import com.chuangke.lowcode.component.ProgressComponent;

/**
 * 数据处理，将数据分模型组装
 */
@Component
@Transactional(rollbackFor = Throwable.class)
@SuppressWarnings({"rawtypes", "unchecked"})
public class BeforeUpdateValidateStatusComponent implements ProgressComponent {

    public void process(LowCodeContext modelContext) {
    	if(CollectionUtils.isEmpty(modelContext.getDatas())) {
    		return ;
    	}
    	
    	List<String> billIdList = getBillIds(modelContext.getDatas()) ;
    	IService service = (IService) SpringContextUtil.getBean(modelContext.getEntityModel().getServiceBeanName());
        QueryWrapper qw = new QueryWrapper();
        qw.select(ColumnConstants.COL_BILL_ID,ColumnConstants.COL_STATUS) ;
        qw.in(ColumnConstants.COL_BILL_ID, billIdList);
        List<BillModel> billList = service.list(qw) ;
        
        Map<String,BillModel> billMap = billList.stream().collect(Collectors.toMap(BillModel::getBillId, a -> a));
        billIdList.forEach(billId -> {
        	if(billMap == null || billMap.get(billId) == null) {
        		throw new ChuangkeException(String.format("单据【%s】不存在", billId)) ;
        	}
        	BillModel billModel = billMap.get(billId) ;
        	if(!OrderStatusEnum.EDIT.getCode().equals(billModel.getStatus())) {
        		throw new ChuangkeException(String.format("单据【%s】非编制中状态，不允许操作", billId)) ;
        	}
        });
        
    }
    private List<String> getBillIds(List datas) {
    	if(datas.get(0) instanceof String) {
    		return datas ;
    	}
    	return (List<String>) datas.stream().map(data -> {
    		BillModel billModel = (BillModel) data;
    		return billModel.getBillId() ;
    	}).collect(Collectors.toList());
    }

}
